from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4
from reportlab.lib.utils import ImageReader
from reportlab.lib import colors

def generate_pdf_report(filename, image_path, defects):
    c = canvas.Canvas(filename, pagesize=A4)
    width, height = A4

    # 标题
    c.setFont("Helvetica-Bold", 20)
    c.drawString(50, height - 50, "Industrial defect inspection report")

    # 图片
    img = ImageReader(image_path)
    img_width = 400
    img_height = 300
    c.drawImage(img, 50, height - 400, width=img_width, height=img_height)

    # 缺陷列表标题
    c.setFont("Helvetica-Bold", 14)
    c.drawString(50, height - 430, "A list of detected defects:")

    # 缺陷内容
    c.setFont("Helvetica", 12)
    y = height - 460
    for defect in defects:
        text = f"Categories: {defect['label']} , Confidence: {defect['confidence']}, ocation: {defect['xyxy']}"
        c.drawString(60, y, text)
        y -= 20
        if y < 50:  # 防止超出页边距，简单分页逻辑
            c.showPage()
            c.setFont("Helvetica", 12)
            y = height - 50

    c.save()

# if __name__ == "__main__":
#     defects = [
#         {"label": "scratch", "confidence": 0.87, "xyxy": [100, 120, 220, 250]},
#         {"label": "crack", "confidence": 0.92, "xyxy": [300, 320, 380, 400]},
#     ]
#     generate_pdf_report("D:\\lab\\detect\\report\\reportpdf\\defect_report.pdf", "D:/lab/detect/report/predict/orange1.jpg", defects)
